package com.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.common.Result;
import com.blog.pojo.Tag;
import com.blog.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 标签相关
 */
@Slf4j
@RestController
@RequestMapping("/tag")
public class TagController {

    @Autowired
    private TagService tagService;

    /**
     * 增添标签
     *
     * @param tag 标签
     * @return Result<String>
     */
    @PostMapping("/save")
    private Result<String> save(@RequestBody Tag tag) {
        LambdaQueryWrapper<Tag> tagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tagLambdaQueryWrapper.eq(Tag::getBlogTagContent, tag.getBlogTagContent());
        Tag tagServiceOne = tagService.getOne(tagLambdaQueryWrapper);
        if (tagServiceOne == null) {
            tagService.save(tag);
            return Result.success("增添成功！");
        } else {
            return Result.error("该标签已存在！请勿重复添加");
        }
    }

    /**
     * 条件分页查询
     *
     * @param page 当前页
     * @param pageSize 页面大小
     * @param bolgTagContent 标签名
     * @return Result<Page>
     */
    @GetMapping("/page")
    private Result<Page> page(int page, int pageSize, String bolgTagContent,Long typeId) {
        return Result.success(tagService.page(page, pageSize, bolgTagContent,typeId));
    }

    /**
     * 删除单个标签
     *
     * @param blogTagId 标签id
     * @return Result<String>
     */
    @DeleteMapping("/delete")
    private Result<String> delete(Long blogTagId) {
        boolean flag = tagService.removeById(blogTagId);
        if (flag)
            return Result.success("删除成功！");
        else
            return Result.error("删除失败！");
    }

    /**
     * 修改标签
     *
     * @param tag 标签对象
     * @return Result<String>
     */
    @PostMapping("/update")
    private Result<String> update(@RequestBody Tag tag) {
        boolean flag = tagService.updateById(tag);
        if (flag)
            return Result.success("修改成功！");
        else
            return Result.error("修改失败！");
    }

    /**
     * 返回对应typeId下的全部tag
     * @param typeId 类型id
     * @return Result<List<Tag>>
     */
    @GetMapping("/listByTypeId")
    private Result<List<Tag>> listByTypeId(@RequestParam String typeId){
        LambdaQueryWrapper<Tag> tagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tagLambdaQueryWrapper.eq(Tag::getTypeId,typeId);
        return Result.success(tagService.list(tagLambdaQueryWrapper));
    }
}
